package com.mlh.handler;

import com.alibaba.fastjson.JSON;
import com.mlh.utils.ResponseResult;
import com.mlh.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 缪林辉
 * @date 2024/3/14 16:01
 * @DESCRIPTION
 */
//需要将该类注入到ioc容器中，不然怎么调用呢？
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {//授权异常
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足");
        // 将result对象转换成json字符串
        String json = JSON.toJSONString(result);
        //这里使用到了WebUtils自定义工具类，将刚刚的json字符串返回
        WebUtils.renderString(response,json);

    }
}